package example.norecursive.trivial;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class TrivialFTAnonymous {
	final static int UP_TO = 7000000; // change together with NO_PRIMES_UP_TO
	final static int NO_PRIMES_UP_TO = 476648;
	private static final int ITERATIONS = 20000000;

	public ReturnValue longComuptation(int upto, int iterations) {
		final int ftIterations = iterations;
		FutureTask<Long> ft = new FutureTask<Long>(new Callable<Long>() {
			public Long call() throws Exception {
				long inside = 0;
				for (int j = 0; j < ftIterations; j++) {
					double x = Math.random();
					double y = Math.random();
					double lenght = x * x + y * y;
					if (lenght < 1.0)
						inside++;
				}
				
				return inside;
			}
		});
		new Thread(ft).start();

		Boolean[] results = new Boolean[upto];
		for (int x = 0; x < results.length; x++)
			results[x] = isPrime(x);

		double pi = 0;
		try {
			pi = ((double) ft.get()) / ftIterations * 4;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		return new ReturnValue(pi, results);
	}

	private boolean isPrime(int x) {
		if (x == 2)
			return true;
		if (x % 2 == 0 || x < 2)
			return false;
		for (long i = 3; i <= Math.sqrt(x); i += 2)
			if (x % i == 0)
				return false;
		return true;
	}

	class ReturnValue {
		double pi;
		Boolean[] primes;

		ReturnValue(double pi, Boolean[] results) {
			this.pi = pi;
			this.primes = results;
		}
	}

	public static void main(String[] args) {
		TrivialFTAnonymous trivial = new TrivialFTAnonymous();

		long startTime = System.nanoTime();
		ReturnValue rv = trivial.longComuptation(UP_TO, ITERATIONS);
		long endTime = System.nanoTime();

		System.out.println("PI: " + rv.pi);

		int numberOfPrimes = 0;
		for (boolean isP : rv.primes)
			if (isP)
				numberOfPrimes++;
		System.out.println("#      primes: " + numberOfPrimes);

		System.out.println("Time: " + (endTime - startTime) / 1000000 + "ms");
	}
}
